package ch.esn.client.presenter;

import ch.esn.client.MainEventBus;
import ch.esn.client.presenter.view_interface.RootViewInterface;
import ch.esn.client.service.UserServiceAsync;
import ch.esn.client.view.RootView;
import ch.esn.shared.gxt.model.UserModel;

import com.extjs.gxt.desktop.client.Shortcut;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.mvp4g.client.annotation.InjectService;
import com.mvp4g.client.annotation.Presenter;
import com.mvp4g.client.presenter.LazyPresenter;

@Presenter(view = RootView.class)
public class RootPresenter extends LazyPresenter<RootViewInterface, MainEventBus> {

	private UserServiceAsync userService;

	private UserModel loggedUser;

	private void bindShortcutsSelectListener() {
		for (Shortcut s : view.getDesktop().getShortcuts()) {
			s.addSelectionListener(new SelectionListener<ComponentEvent>() {
				@Override
				public void componentSelected(ComponentEvent ce) {
					eventBus.itemSelected(ce);
				}
			});
		}
	}

	@Override
	public void bindView() {
		super.bindView();

		bindShortcutsSelectListener();
	}

	@Override
	public void createPresenter() {
		super.createPresenter();

	}

	public void onBasicUserDataLoaded() {
		view.unMaskAll();
	}

	public void onInitApp() {
		eventBus.loadLoggedUserData();
	}

	public void onItemSelected(ComponentEvent ce) {
		proceedItemSelected(ce.getComponent().getId());
	}

	public void onLoadLoggedUserData() {
		userService.getLoggedUser(new AsyncCallback<UserModel>() {

			public void onFailure(Throwable caught) {
				com.google.gwt.user.client.Window.alert("Error while retrieving logged user!");
			}

			public void onSuccess(UserModel result) {
				loggedUser = result;

				String heading = "Logged as " + loggedUser.get("email");

				view.getDesktop().getStartMenu().setHeading(heading);

				eventBus.basicUserDataLoaded();
			}
		});
	}

	public void onShowWindow(Window w) {
		if (!view.getDesktop().getWindows().contains(w)) {
			view.getDesktop().addWindow(w);
		}

		if (!w.isVisible()) {
			w.show();
		} else {
			w.toFront();
		}
	}

	@SuppressWarnings("static-access")
	private void proceedItemSelected(String componentId) {
		if (view.SHORTCUT_EDIT_PROFILE_ID.equals(componentId) || view.MENU_EDIT_PROFILE_ID.equals(componentId)) {
			eventBus.showEditProfileWindow();
		} else if (view.SHORTCUT_LOGOUT_ID.equals(componentId) || view.MENU_LOGOUT_ID.equals(componentId)) {
			eventBus.logout();
		}
	}

	@InjectService
	public void setUserService(UserServiceAsync userService) {
		this.userService = userService;
	}
}
